package com.chilli.cosima.action.login;

import java.util.ArrayList;
import java.util.List;

import com.chilli.cosima.data.bean.TPower;
import com.chilli.cosima.service.LoginService;
import com.chilli.cosima.utils.SpringUtils;

public class Node
{
	private TPower power;

	private List<Node> childrenList;

	public Node(TPower power)
	{
		this.power = power;
	}

	public void addChild(Node node)
	{
		if (childrenList == null)
		{
			childrenList = new ArrayList<Node>();
		}
		childrenList.add(node);
	}

	/**
	 * 列出所有的下级权限
	 * 
	 * @return [参数说明]
	 * 
	 * @return List<Node> [返回类型说明]
	 * @exception throws
	 *                [违例类型] [违例说明]
	 * @see [类、类#方法、类#成员]
	 */
	public List<Node> listNodes()
	{
		LoginService loginService = (LoginService) SpringUtils
				.getBean("loginService");
		List<TPower> list = loginService.findChildrenPowerByParentId(this.power
				.getPowerid());
		if (null == list || list.size() < 1)
		{
			return new ArrayList<Node>();
		} else
		{
			if (this.childrenList != null && this.childrenList.size() > 0)
			{
				this.childrenList.clear();
			}
			for (int i = 0; i < list.size(); i++)
			{
				TPower power = list.get(i);
				Node node = new Node(power);
				this.addChild(node);
			}
			return this.childrenList;
		}

	}

	/**
	 * 列出在权限范围内的下级权限
	 * 
	 * @return [参数说明]
	 * 
	 * @return List<Node> [返回类型说明]
	 * @exception throws
	 *                [违例类型] [违例说明]
	 * @see [类、类#方法、类#成员]
	 */
	public List<Node> listNodes(List<String> powerList)
	{
		LoginService loginService = (LoginService) SpringUtils
				.getBean("loginService");
		List<TPower> list = loginService.findChildrenPowerByParentId(this.power
				.getPowerid());
		if (null == list || list.size() < 1)
		{
			return new ArrayList<Node>();
		} else
		{
			if (this.childrenList != null && this.childrenList.size() > 0)
			{
				this.childrenList.clear();
			}
			for (int i = 0; i < list.size(); i++)
			{
				TPower power = list.get(i);
				if (powerList != null && powerList.contains(power.getPowerid()))
				{
					Node node = new Node(power);
					this.addChild(node);
				}

			}
			return this.childrenList;
		}

	}

	public TPower getPower()
	{
		return power;
	}

	public void setPower(TPower power)
	{
		this.power = power;
	}

	public boolean isLeaf()
	{
		if (this.childrenList == null)
		{
			this.childrenList = listNodes();
		}
		if (null == this.childrenList || this.childrenList.size() < 1)
		{
			return true;
		} else
		{
			return false;
		}
	}

	public List<Node> getChildrenList()
	{
		return childrenList;
	}

	public void setChildrenList(List<Node> childrenList)
	{
		this.childrenList = childrenList;
	}

}
